import { Alert, Button, Checkbox, Input } from 'antd';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import React, { Component } from 'react';
import Link from 'umi/link';
import { connect } from 'dva';
import LoginComponents from './components/Login';
import RegisterComponents from './components/Register';
import styles from './style.less';
const { Tab, UserName, Password, Mobile, Captcha, Submit } = LoginComponents;
import Router from "umi/router";
import {string} from "prop-types";
@connect(({ login, loading }) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))
class Login extends Component {
  loginForm = undefined;
  state = {
    type: 'account',
    autoLogin: true,
    flag: 1,
    pw1: '',
    pw2: '',
    userName: '',
    imgInfo: {},
    imgCode: '',
    tenantUrl:window.location.hash.indexOf("tenantUrl") !== -1 ? window.location.hash.split("?")[1].split("=")[1] :'default'
  };
  changeAutoLogin = e => {
    this.setState({
      autoLogin: e.target.checked,
    });
  };
  handleSubmit = (err, values) => {
    const { type } = this.state;
    const tenantUrl = window.location.hash.indexOf("tenantUrl") !== -1 ? window.location.hash.split("?")[1].split("=")[1] :'default'

    if (!err) {
      const { dispatch } = this.props;
      values.password = this.md5(values.password);
      localStorage.setItem('tenantUrl',tenantUrl)
      dispatch({
        type: 'login/login',
        payload: { ...values, tenantUrl },
      });
    }
  };
  componentDidMount() {
    // var tenantUrl = ''
    // if(localStorage.getItem("tenantUrl")){
    //   if (window.location.hash.indexOf("tenantUrl") !== -1 && window.location.hash.split("?")[1].split("=")[1] !== localStorage.getItem("tenantUrl")){
    //     tenantUrl = window.location.hash.split("?")[1].split("=")[1]
    //   }else {
    //     tenantUrl = localStorage.getItem("tenantUrl")
    //   }
    // }else {
    //   if (window.location.hash.indexOf("tenantUrl") !== -1){
    //     tenantUrl = window.location.hash.split("?")[1].split("=")[1]
    //   }else {
    //     tenantUrl = 'default'
    //   }
    // }
    // if (tenantUrl === 'null' || tenantUrl === null){
    //   tenantUrl = 'default'
    // }
    // Router.push(`/user/login?tenantUrl=` + tenantUrl);
  }

  onTabChange = type => {
    this.setState({
      type,
    });
  };
  onGetCaptcha = () =>
    new Promise((resolve, reject) => {
      if (!this.loginForm) {
        return;
      }

      this.loginForm.validateFields(['mobile'], {}, async (err, values) => {
        if (err) {
          reject(err);
        } else {
          const { dispatch } = this.props;

          try {
            const success = await dispatch({
              type: 'login/getCaptcha',
              payload: values.mobile,
            });
            resolve(!!success);
          } catch (error) {
            reject(error);
          }
        }
      });
    });
  renderMessage = content => (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
  onChangeFlag(flag) {
    this.setState({
      pw1: '',
      pw2: '',
      userName: '',
      flag: flag,
    });
  }
  onUserNameChange(e) {
    let value = e.target.value;
    this.setState({
      nameCheck: null,
      userName: value,
    });
  }

  onPw1Change(e) {
    let value = e.target.value;
    this.setState({
      pw1Check: null,
      pw1: value,
    });
  }

  onPw2Change(e) {
    let value = e.target.value;
    this.setState({
      pw2Check: null,
      pw2: value,
    });
  }
  render() {
    const { userLogin, submitting } = this.props;
    const { status, type: loginType } = userLogin;
    const { type, autoLogin,pw1, pw2, userName, imgInfo, imgCode } = this.state;
    return (
      <div className={styles.main}>
        {this.state.flag ===1 ? (<><LoginComponents
          defaultActiveKey={type}
          onTabChange={this.onTabChange}
          onSubmit={this.handleSubmit}
          onCreate={form => {
            this.loginForm = form;
          }}
        >
          {/* <h2 style={{textAlign:'center'}}>
          <FormattedMessage id="user-register.login.login" />
        </h2>
          <Tab
            key="account"
            tab={formatMessage({
              id: 'user-login.login.tab-login-credentials',
            })}
          > */}
          {status === 'error' &&
            loginType === 'account' &&
            !submitting &&
            this.renderMessage(
              formatMessage({
                id: 'user-login.login.message-invalid-credentials',
              }),
            )}
          <UserName
            name="username"
            placeholder={`${formatMessage({
              id: 'user-login.login.userName',
            })}`}
            rules={[
              {
                required: true,
                pattern: /^\w{4,12}$/,
                message: formatMessage({
                  id: 'user-login.userName.required',
                }),
              },
            ]}
          />
          <Password
            name="password"
            placeholder={`${formatMessage({
              id: 'user-login.login.password',
            })}`}
            rules={[
              {
                required: true,
                message: formatMessage({
                  id: 'user-login.password.required',
                }),
              },
            ]}
            onPressEnter={e => {
              e.preventDefault();

              if (this.loginForm) {
                this.loginForm.validateFields(this.handleSubmit);
              }
            }}
          />
          {/*</Tab>*/}
          {/*<Tab
            key="mobile"
            tab={formatMessage({
              id: 'user-login.login.tab-login-mobile',
            })}
          >
            {status === 'error' &&
              loginType === 'mobile' &&
              !submitting &&
              this.renderMessage(
                formatMessage({
                  id: 'user-login.login.message-invalid-verification-code',
                }),
              )}
            <Mobile
              name="mobile"
              placeholder={formatMessage({
                id: 'user-login.phone-number.placeholder',
              })}
              rules={[
                {
                  required: true,
                  message: formatMessage({
                    id: 'user-login.phone-number.required',
                  }),
                },
                {
                  pattern: /^1\d{10}$/,
                  message: formatMessage({
                    id: 'user-login.phone-number.wrong-format',
                  }),
                },
              ]}
            />
            <Captcha
              name="captcha"
              placeholder={formatMessage({
                id: 'user-login.verification-code.placeholder',
              })}
              countDown={120}
              onGetCaptcha={this.onGetCaptcha}
              getCaptchaButtonText={formatMessage({
                id: 'user-login.form.get-captcha',
              })}
              getCaptchaSecondText={formatMessage({
                id: 'user-login.captcha.second',
              })}
              rules={[
                {
                  required: true,
                  message: formatMessage({
                    id: 'user-login.verification-code.required',
                  }),
                },
              ]}
            />
          </Tab>*/}
          {/*<div>
            <Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>
              <FormattedMessage id="user-login.login.remember-me" />
            </Checkbox>
            <a
              style={{
                float: 'right',
              }}
              href=""
            >
              <FormattedMessage id="user-login.login.forgot-password" />
            </a>
          </div>*/}
          <Submit loading={submitting}>
            <FormattedMessage id="user-login.login.login" />
          </Submit>
          <div className={styles.other}>
            {/*<FormattedMessage id="user-login.login.sign-in-with" />
            <Icon type="alipay-circle" className={styles.icon} theme="outlined" />
            <Icon type="taobao-circle" className={styles.icon} theme="outlined" />
            <Icon type="weibo-circle" className={styles.icon} theme="outlined" />*/}
            {/* <Link className={styles.register} to="/user/register" type='link'>
              <FormattedMessage id="user-login.login.signup" />
            </Link> */}
          </div>
        </LoginComponents>
        <div className={styles.kg_sys_login_opt}>
          <div
            onClick={this.onChangeFlag.bind(this, 2)}
            className={styles.kg_sys_login_opt_txt}
          >
            没有帐号
          </div>
        </div></>):(
          <div className={styles.kg_sys_login_inner}>
            <RegisterComponents></RegisterComponents>
            {/*<div className={styles.kg_sys_login_title}>*/}
            {/*  <img className={styles.kg_sys_login_ico} src={titleIcoUrl} />*/}
            {/*</div>*/}


            {/*<div className={styles.kg_sys_login_input}>*/}
            {/*  <Input*/}
            {/*    size="large"*/}
            {/*    prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}*/}
            {/*    placeholder="请输入用户名"*/}
            {/*    // suffix={this.state.nameCheck}*/}
            {/*    value={userName}*/}
            {/*    onChange={this.onUserNameChange.bind(this)}*/}
            {/*  />*/}
            {/*</div>*/}
            {/*<div className={styles.kg_sys_login_input}>*/}
            {/*  <Input*/}
            {/*    size="large"*/}
            {/*    prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}*/}
            {/*    placeholder="请输入密码"*/}
            {/*    // suffix={this.state.pw1Check}*/}
            {/*    value={pw1}*/}
            {/*    type="password"*/}
            {/*    onChange={this.onPw1Change.bind(this)}*/}
            {/*  />*/}
            {/*</div>*/}
            {/*<div className={styles.kg_sys_login_input}>*/}
            {/*  <Input*/}
            {/*    size="large"*/}
            {/*    prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}*/}
            {/*    placeholder="再次输入密码"*/}
            {/*    // suffix={this.state.pw2Check}*/}
            {/*    value={pw2}*/}
            {/*    type="password"*/}
            {/*    onChange={this.onPw2Change.bind(this)}*/}
            {/*  />*/}
            {/*</div>*/}
            {/*<Button*/}
            {/*  type="primary"*/}
            {/*  style={{ width: '100%', marginTop: '24px' }}*/}
            {/*  size="large"*/}
            {/*  // onClick={this.onRegisterClick.bind(this)}*/}
            {/*>*/}
            {/*  注 册*/}
            {/*</Button>*/}
            <div className={styles.kg_sys_login_opt}>
              <div
                onClick={this.onChangeFlag.bind(this, 1)}
                className={styles.kg_sys_login_opt_txt}
              >
                已有帐号
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }
}

export default Login;
